const { ForbiddenError } = require("./error")
const { pathToRegexp } = require("path-to-regexp")
const jwt = require("./jwt")

// 需不需要token认证访问的接口

const needTokenApi = [
    { method: "POST", path: "/api/banner" },
    { method: "POST", path: "/api/upload" },
    { method: "GET", path: "/api/stu" },
    { method: "GET", path: "/api/admin/whoami" },
    { method: "DELETE", path: "/api/blog/:id" },
    { method: "PUT", path: "/api/blog/:id" },
    { method: "DELETE", path: "/api/blogtype/:id" },
    { method: "PUT", path: "/api/blogtype/:id" },
    { method: "post", path: "/api/blogtype" },
    { method: "POST", path: "/api/project" },
    { method: "DELETE", path: "/api/project/:id" },
    { method: "PUT", path: "/api/project/:id" }
];


// 处理没有认证的情况

function handleNonToken(req, res, next) {
    res.send(new ForbiddenError("you dont have any token to access the api").toResponseJSONError())
}

module.exports = (req, res, next) => {
    // /api/student/:id 和  /api/student/1771
    const apis = needTokenApi.filter((api) => {
        const reg = pathToRegexp(api.path);
        return api.method === req.method && reg.test(req.path);
    });
    if (apis.length === 0) {
        next();
        return;
    }
    let result = jwt.verification(req)
    if (!result) {
        // 获取token验证结果
        handleNonToken(req, res, next)
    } else {
        req.info = result
        next()

    }

}